'''
Created on Mar 8, 2010

@author: Nick Heiner
'''
from models import InCart
from google.appengine.api import mail, memcache

class CheckOut():
    """ Checks out a cart """
    
    def checkout(self, user, anon_key=None):
        if not anon_key:
            cart = InCart.gql("WHERE owner = :1", user)
        else:
            cart = memcache.get(anon_key)
            
        errors = self.validateCartItems(cart)
        if errors:
            return errors
        
#        I wanted to send out a description of what was bought in the mail, but couldn't quite get it to work.    
#        items_for_email = []
        sum = 0
        
        for cartEntry in cart:
            cartEntry.item.quantity -= cartEntry.quantity # this is safe, because validation has already occurred
            cartEntry.item.put() # update the item now that we've changed the quantity
            sum += cartEntry.item.price * cartEntry.quantity
#            items_for_email.append({'name': cartEntry.item.name,
#                                    'quantity': cartEntry.quantity,
#                                    'cost': cartEntry.item.price,
#                                    })
            
            if not anon_key:
                cartEntry.delete()
        
        if anon_key: # if anonymous, remove this cart from the memcache
            memcache.delete(anon_key)
            
#        email_listing = []
#        for purchase in items_for_email:
#            email_listing.append("%s %d $%d (Total: $%d)" % 
#                                    (purchase['name'], purchase['quantity'], purchase['cost'], purchase['quantity'] * purchase['cost']))
            
        msg = mail.EmailMessage()
        msg.subject = "Cornell Store cart order processed"
        msg.to = user.email()
        msg.sender = "nick.heiner@gmail.com"
        msg.body = "Your order has been processed. It will be ready for pickup in Ithaca whenever you feel like it. Please bring $%d" % sum 
        msg.send()

        return ["Checkout complete. You will get email confirmation shortly."]
        
    def validateCartItems(self, cart):
        errors = []
        for cartEntry in cart:
            if cartEntry.quantity > cartEntry.item.quantity:
                errors.append("There is only %d of %s available, but the cart contained %d" % (cartEntry.item.quantity, cartEntry.item.name, cartEntry.quantity))
            
        return errors